package com.demo.javase.day50;

/**
 * 性能测试（对比10万次字符串连接各自需要耗时多久）结论如下：
 * String time耗时: 26374ms
 * StringBuilder time耗时: 2ms
 * StringBuffer time耗时: 6ms
 *
 * @author bug菌
 * @version 1.0
 * @date 2023/10/12 14:33
 */
public class StringPerformanceTest {

    private static final int ITERATIONS = 100000;
    private static final String STR_TO_APPEND = "hello";

    public static void main(String[] args) {
        String string = "hello";

        long start = System.currentTimeMillis();
        for (int i = 0; i < ITERATIONS; i++) {
            string = string + STR_TO_APPEND;
        }
        long end = System.currentTimeMillis();
        System.out.println("String time耗时: " + (end - start) + "ms");

        StringBuilder stringBuilder = new StringBuilder("hello");
        start = System.currentTimeMillis();
        for (int i = 0; i < ITERATIONS; i++) {
            stringBuilder.append(STR_TO_APPEND);
        }
        end = System.currentTimeMillis();
        System.out.println("StringBuilder time耗时: " + (end - start) + "ms");

        StringBuffer stringBuffer = new StringBuffer("hello");
        start = System.currentTimeMillis();
        for (int i = 0; i < ITERATIONS; i++) {
            stringBuffer.append(STR_TO_APPEND);
        }
        end = System.currentTimeMillis();
        System.out.println("StringBuffer time耗时: " + (end - start) + "ms");
    }
}
